import Vue from 'vue'
import axios from 'axios'
import Qs from 'qs'
import router from '@/router'
import Cookies from 'js-cookie'
import { Message } from 'iview'
import config from '@/config'
const baseUrl = config.baseUrl
console.log(Vue.prototype.$config)
// 不需要做重复判断的接口
const COUNT_WHITE = [
  Vue.prototype.$config.uploadImg
]
class HttpRequest {
  count = new Set(); // 防止重复提交
  constructor (baseUrl = baseURL) {
    this.baseUrl = baseUrl
    this.queue = {}
  }
  getInsideConfig () {
    const config = {
      baseURL: this.baseUrl,
      headers: {
        //
      }
    }
    return config
  }
  destroy (url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {
      // Spin.hide()
    }
  }
  interceptors (instance, url) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      // 添加全局的loading...
      if (!Object.keys(this.queue).length) {
        // Spin.show() // 不建议开启，因为界面不友好
      }
      this.queue[url] = true
      if (Cookies.get('token')) {
        config.headers.token = Cookies.get('token')
        config.headers.appId = '03e35b82-9985-44b6-8d44-44a1c4fb9609'
      }
      return config
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      this.destroy(url)
      const { data, status } = res
      return { data, status }
    }, error => {
      this.destroy(url)
      let errorInfo = error.response
      if (!errorInfo) {
        const { request: { statusText, status }, config } = JSON.parse(JSON.stringify(error))
        errorInfo = {
          statusText,
          status,
          request: { responseURL: config.url }
        }
      }
      Message.error((error.response && error.response.data && error.response.data.message) || (error.response && error.response.data && error.response.data.error) || (error.message))
      if (error.response && error.response.status === 500) {
        router.push({
          name: 'error_500'
        })
      }
      if (error.response && error.response.status === 401) {
        router.push({
          name: 'error_401'
        })
      }
      return Promise.reject(error)
    })
  }
  request (options) {
    let formData = {}
    if (options.data instanceof FormData) {
      options.data.forEach && options.data.forEach((value, key) => {
        Reflect.set(formData, key, value)
      })
    }
    // let key = JSON.stringify(Object.assign(formData, options))
    let key = Qs.stringify(Object.assign(formData, options))
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    let promise = new Promise((resolve, reject) => {
      // 不需要做重复判断的接口
      if (!COUNT_WHITE.includes(options.url)) {
        if (this.count.has(key)) return reject(new Error('重复的请求'))
        this.count.add(key)
      }
      instance(options).then(res => {
        resolve(res)
      }).catch(err => {
        reject(err)
      }).finally(() => {
        // setTimeout(() => {
        if (this.count.has(key)) this.count.delete(key)
        // }, 50)
      })
    })

    return promise
  }
}
const request = new HttpRequest(baseUrl)
export default request
